package com.link.base.base.coupons.controller;

import com.link.base.core.basic.util.YmlConstants;
import com.link.base.user.model.CoreUser;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.coupons.model.CollectRecord;
import com.link.base.base.coupons.service.CollectRecordService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.core.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>优惠券—领取记录Controller</p>
 * @author wangdawei
 * @date 2018/6/10
 */

@Controller
@RequestMapping("/link/collectRecord")
public class CollectRecordController extends BasicController<CollectRecord> {

    @Resource
    private CollectRecordService collectRecordService;

    @Resource
    private AccountService accountService;

    @Override
    public BasicService<CollectRecord> getBasicService() throws Exception {
        return collectRecordService;
    }

    /**
     * 生成二维码图片，如果二维码图片不存在创建二维码图片，并存入领取记录明细表
     * @author wangdawei
     * @param id
     * @date: 2018/6/2
     */
    @RequestMapping(value = "/getCodePic")
    @ResponseBody
    public Map<String, Object> pcGetCoupon(@JsonParam QueryParams qps, Long id, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        Long corpid = Long.parseLong(request.getParameter("corpid"));
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CollectRecord entity = new CollectRecord();
            entity.setId(id);
            entity.setLoginCorpId(corpid);
            entity.setCorpid(corpid);
            CollectRecord collectRecord = collectRecordService.queryById(entity);
            //不存在二维码图片就创建二维码图片。
            if ("".equals(collectRecord.getCodeImgSaveUrl()) || collectRecord.getCodeImgSaveUrl() == null) {
                CoreUser user = UserUtil.getUser();
                Long strJson = id;
                //二维码存放位置,静态路径。
                String file = "/web/file/saleactivity/" + user.getCorpid() + "/";
                String fileName = String.valueOf(id) + "_" + DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss") + ".png";
                //二维码的本地路径（默认Portal文件系统根目录）
                QRCodeUtil.tomakeMode(String.valueOf(strJson), YmlConstants.getPortalShareFileDir() + file, fileName, 140, 140);
                collectRecord.setCodeImgSaveUrl(file + fileName);
                //保存活动
                collectRecord.setCorpid(corpid);
                collectRecord.setLoginCorpId(corpid);
                collectRecord.setPostnId(0L);
                collectRecord.setAnonymousFlag("Y");
                collectRecordService.update(collectRecord);
            }
            CollectRecord collectRecordNew = collectRecordService.queryById(entity);
            collectRecordNew.setAnonymousFlag("Y");
            result.put("success", true);
            result.put("result", collectRecordNew.getCodeImgSaveUrl());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 批量更新领取优惠券的微信code
     * @author KuangRuifeng
     * @date 2018年12月4日
     * @return 更新结果
     */
    @RequestMapping(value = "/updWeChatCodes")
    @ResponseBody
    public Map<String, Object> updWeChatCodes(@RequestBody CollectRecord collectRecord, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(2);
        try {
            List<CollectRecord> collectRecords = collectRecord.getCollectRecordList();
            collectRecordService.updWeChatCodes(collectRecords);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 查询所有与当前用户相同会员id的客户优惠券
     *
     * @author KuangRuifeng
     * @date 2018年12月12日
     */
    @RequestMapping(value = "/queryByMemberPage")
    @ResponseBody
    public Map<String, Object> queryByMemberPage(@JsonParam QueryParams qps, @JsonParam CollectRecord collectRecord, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            String equalOp = "=";
            String inOp = "in";
            // 先查询当前用户信息,若用户存在手机号，查询此手机号码的所有消费者，若不存在，再根据会员id查询
            Long accntId = UserUtil.getUser().getAcctId();
            Account account = accountService.queryById(accntId);
            String mobilePhone = account.getMobilePhone1();
            Long memberId = 0L;
            // 筛选客户的属性字段
            String property = "accntId";
            Filter filter;
            if (StringUtils.isNotBlank(mobilePhone)) {
                // 存在手机号码，查询所有此手机号码的消费者
                Account acc = new Account();
                acc.setMobilePhone1(account.getMobilePhone1());
                acc.setPageFlag(false);
                List<Account> accountList = accountService.queryByExamplePage(acc);
                // 构造accntId数组
                List<Long> ids = accountList.stream().map(Account::getId).collect(Collectors.toList());
                filter = new Filter(property, inOp, String.valueOf(ids));
            } else if (memberId != null) {
                // 存在会员id，查询所有此会员的消费者
                Account acc = new Account();
                acc.setPageFlag(false);
                List<Account> accountList = accountService.queryByExamplePage(acc);
                // 构造accntId数组
                List<Long> ids = accountList.stream().map(Account::getId).collect(Collectors.toList());
                filter = new Filter(property, inOp, String.valueOf(ids));
            } else {
                // 手机号和会员id都不存在
                filter = new Filter(property, equalOp, String.valueOf(accntId));
            }
            qps.addFilter(filter);
            result = super.queryByExamplePage(qps, collectRecord, session, request, response);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 更新优惠券查看状态
     * @author KuangRuifeng
     * @date 2018年12月13日
     */
    @RequestMapping(value = "/updateNoticed")
    @ResponseBody
    public Map<String, Object> updateNoticed(@RequestBody CollectRecord collectRecord, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(2);
        try {
            collectRecordService.updateNoticed(collectRecord);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 查询优惠券领取记录监控列表
     * @author 王艳
     * @date 2018年12月19日
     */
    @RequestMapping({"/queryListPage"})
    @ResponseBody
    public Map<String, Object> queryListPage(@JsonParam QueryParams qps, @JsonParam CollectRecord entity,
                                             HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap();

        try {
            qps.preDealSecurity(request);
            CollectRecord temp = (CollectRecord) BasicModel.transformClass(entity, qps);
            this.beforQueryAllOrExample(temp, request);
            this.beforQueryExample(temp, request);
            List<CollectRecord> list = collectRecordService.queryListPage(temp);
            result.put("success", true);
            result.put("rows", list);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("total", getCount(temp, list.size()));
        } catch (ServiceException var9) {
            result.put("success", false);
            result.put("rows", new ArrayList());
            result.put("result", var9.getMessage());
            result.put("detailMessage", var9.getMessage());
        } catch (Exception var10) {
            result.put("success", false);
            result.put("rows", new ArrayList());
            result.put("result", var10.getMessage());
        }

        return result;
    }

    /**
     * 优惠券领取记录监控列表导出
     * @author 王艳
     * @date 2018年12月19日
     */
    @RequestMapping({"/queryListPage/exportData"})
    @ResponseBody
    public Map<String, Object> exportListData(@JsonParam CollectRecord entity, @JsonParam QueryParams qps,
                                              HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap();

        try {
            qps.preDealSecurity(request);
            CoreUser user = UserUtil.getUser();
            if (null != user) {
                user.setExportType(qps.getExportFileType());
            }

            ExportWriter exportWriter;
            if ("xlsx".equals(user.getExportType())) {
                exportWriter = ExportFactory.newExcelInstance(qps);
            } else {
                exportWriter = ExportFactory.newInstance(qps);
            }

            CollectRecord temp = (CollectRecord) BasicModel.transformClass(entity, qps);

            while (!qps.getStopExport()) {
                this.beforQueryAllOrExample(temp, request);
                this.beforQueryExample(temp, request);
                List<CollectRecord> list = collectRecordService.queryListPage(temp);
                if (qps.getPage() == 1) {
                    qps.setTotal(temp.getTotal());
                }

                exportWriter.wirteData(list);
                if ("Y".equals(qps.getExportCurrentPage())) {
                    break;
                }

                temp.setPage(qps.getPage());
                temp.setTotalFlag(qps.getTotalFlag());
            }

            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (ServiceException var11) {
            result.put("success", false);
            result.put("result", var11.getMessage());
            result.put("detailMessage", var11.getMessage());
        } catch (Exception var12) {
            result.put("success", false);
            result.put("result", var12.getMessage());
        }

        return result;
    }

    /**
     * 查询优惠券领取记录监控详情
     * @author 王艳
     * @date 2018年12月19日
     */
    @RequestMapping({"/queryDetailById"})
    @ResponseBody
    public Map<String, Object> queryDetailById(@JsonParam CollectRecord entity,
                                               HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap();

        try {
            CollectRecord record = collectRecordService.queryDetailById(entity);
            List<CollectRecord> list = new ArrayList();
            list.add(record);
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            result.put("result", record);
            result.put("success", true);
        } catch (ServiceException var8) {
            result.put("success", false);
            result.put("result", var8.getMessage());
            result.put("detailMessage", var8.getMessage());
        } catch (Exception var9) {
            result.put("success", false);
            result.put("result", var9.getMessage());
        }

        return result;
    }

    /**
     * 会员-发放优惠券
     *
     * @author lijie
     * @param entity
     * @date   2019/8/09 12:00
     */
    @RequestMapping("/insertOtherByTrans")
    @ResponseBody
    public Map<String, Object> insertOtherByTrans(@RequestBody CollectRecord entity, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            collectRecordService.insert(entity);
            result.put("success", true);
        } catch (Exception var9) {
            result.put("success", false);
            result.put("result", var9.getMessage());
        }
        return result;
    }
}
